package com.xiaoxiao.springbootstudy.controller;

import com.xiaoxiao.springbootstudy.pojo.Customer;
import com.xiaoxiao.springbootstudy.pojo.vo.CountResult;
import com.xiaoxiao.springbootstudy.service.CustomerService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @PostMapping("/addCust")
    public Map<String, Object> addCustomer(@RequestBody Customer customer) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("msg", "操作失败");
        try {
            customerService.save(customer);
            map.put("code", 200);
            map.put("msg", "OK");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @GetMapping("/custList")
    public Map<String, Object> getCustList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        return customerService.getCustList(pageNum, pageSize);
    }

    @PostMapping("/updateCust")
    public Map<String, Object> updateCust(@RequestBody Customer customer) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("msg", "更新失败");

        try {
            customerService.updateById(customer);
            map.put("code", 200);
            map.put("msg", "客户信息修改成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @GetMapping("/deleteCust")
    public  Map<String, Object> deleteCust(@RequestParam Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("msg", "删除失败");

        try {
            customerService.removeById(id);
            map.put("code", 200);
            map.put("msg", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }


    @GetMapping("/listAllCust")
    public Map<String, Object> getCustIdNameList() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("msg", "获取列表失败");
        try {
            map.put("code", 200);
            map.put("data", customerService.getCustIdNameList());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @GetMapping("/countCust")
    public List<CountResult> countCust(){

        return customerService.countCustService();
    }
}
